import { defineStore } from 'pinia';
import { ref } from 'vue';
import axios from 'axios';

interface Algorithm {
  id: number;
  algorithmName: string;
  coverUrl: string;
  exampleUrl: string;
  apiAddress: string;
  description: string;
}

interface AlgorithmScenario {
  id: number;
  scenarioName: string;
  scenarioDescription: string;
  status: string;
  algorithms: Algorithm[];  // 包含算法数组
}

export const useAlgorStore = defineStore('algor', () => {
  // State
  const algorithmScenario = ref<AlgorithmScenario[]>([]);

  // Actions
  const setAlgorData = (data: AlgorithmScenario[]) => {
    algorithmScenario.value = data || [];
  };

  // Fetch data from API and set to store
  const fetchAlgorData = async () => {
    try {
      const response = await axios.get('/api/auth'); // 替换为实际的接口地址
      setAlgorData(response.data);  // 假设接口返回的数据结构与你的需求一致
    } catch (error) {
      console.error('Failed to fetch auth data:', error);
    }
  };

  // Clear the algorithm data
  const clearAlgorData = () => {
    algorithmScenario.value = [];
  };

  // Logout - Clears the store and local storage
  const logout = () => {
    clearAlgorData();  // 清理 Pinia 仓库
    localStorage.clear();  // 清理本地存储
  };

  // Add a new algorithm to a specific scenario
  const addAlgorithm = (scenarioId: number, algorithm: Algorithm) => {
    const scenario = algorithmScenario.value.find((s) => s.id === scenarioId);
    if (scenario) {
      scenario.algorithms.push(algorithm);
    }
  };

  // Remove an algorithm from a specific scenario
  const removeAlgorithm = (scenarioId: number, algorithmId: number) => {
    const scenario = algorithmScenario.value.find((s) => s.id === scenarioId);
    if (scenario) {
      scenario.algorithms = scenario.algorithms.filter(
        (algorithm) => algorithm.id !== algorithmId
      );
    }
  };

  // Update a specific scenario's details
  const updateScenario = (scenarioId: number, updatedData: Partial<AlgorithmScenario>) => {
    const scenario = algorithmScenario.value.find((s) => s.id === scenarioId);
    if (scenario) {
      Object.assign(scenario, updatedData);
    }
  };

  // Getters
  const getScenarioById = (id: number) => {
    return algorithmScenario.value.find((scenario) => scenario.id === id);
  };

  const getAlgorithmsByScenarioId = (scenarioId: number) => {
    const scenario = algorithmScenario.value.find((s) => s.id === scenarioId);
    return scenario ? scenario.algorithms : [];
  };

  return {
    algorithmScenario,
    setAlgorData,
    fetchAlgorData,
    clearAlgorData,
    logout,
    addAlgorithm,
    removeAlgorithm,
    updateScenario,
    getScenarioById,
    getAlgorithmsByScenarioId,
  };
}, {
  persist: {
    enabled: true,  // Persist store data to localStorage
  } as any,
});
